package cn.snailhd.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Logger;

public class MutilThreadDownload implements Runnable{
	private Logger log = Logger.getLogger(this.getClass().getName());
	private String url;  
	private String file;
	private int offset;
	private int length;
	private CountDownLatch end;
	
	public MutilThreadDownload(String url,String file,int offset,int length,CountDownLatch end){
		this.url = url;
		this.file = file;
		this.offset = offset;
		this.length = length;
		this.end = end;
	}

	@Override
	public void run() {
		HttpRequest request = null;
		try {
			request = new HttpRequest(url);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	
		HttpURLConnection  connection = request.getConnection();
		
		BufferedInputStream bis  = null;
		RandomAccessFile raf  = null;
		
		byte[] buff = new byte[length];
		int len=0;
		int size=0;
		try {
			bis = new BufferedInputStream(connection.getInputStream(),1024*1024);
			raf = new RandomAccessFile(file, "rw");
			bis.skip(offset);
			while((len = bis.read(buff))!=-1){
				
				raf.seek(offset);
				if((size+len)>length){
					raf.write(buff, 0, length-size);
					break;
				}else{					
					raf.write(buff,0,len);
				}
				offset+=len;
				size+=len;
				log.info("已下载"+size*100/length+"%");
			}		
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			IoUtils.close(bis);
			try {
				raf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		log.info("end:"+Thread.currentThread().getName());
		end.countDown();
	}
	
}
